<template>
  <el-card>
    <el-button type="primary" :icon="Plus" @click="showSaveDialog"
      >添加品牌</el-button
    >

    <!-- 
      el-table
        data 要渲染的数据
        border 带边框

        el-table-column 列
          type="index" 渲染序号
          label 列的标题
          width 列宽
          align 对齐方式
          prop 要渲染数据中哪个属性的值

          如果只要渲染纯数据，直接prop
          如果要渲染的一些其他结构（组件），用默认插槽
    -->
    <el-table :data="trademarkList" border class="trademark-table">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO" prop="logoUrl">
        <template #default="{ row }">
          <img :src="row.logoUrl" :alt="row.tmName" class="trademark-img" />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <!-- 
          默认插槽 + 作用域插槽
            scope
              $index: 要渲染数据的下标
              row:    要渲染的整个数据
         -->
        <template #default="{ row }">
          <!-- <template v-slot="scope"> -->
          <el-tooltip content="修改品牌" placement="top" effect="light">
            <el-button
              size="small"
              type="warning"
              :icon="Edit"
              @click="showUpdateDialog(row)"
            />
          </el-tooltip>

          <el-tooltip content="删除品牌" placement="top" effect="light">
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              @click="delTrademark(row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      layout="prev, pager, next, jumper, total, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
  <el-dialog
    v-model="visible"
    :title="`${trademarkFormData.id ? '修改' : '添加'}品牌`"
  >
    <!-- 默认插槽给内容区使用 -->
    <el-form
      ref="trademarkFormRef"
      :model="trademarkFormData"
      :rules="trademarkFormRules"
      label-width="90px"
    >
      <!-- 
        prop 使用哪个规则进行校验
       -->
      <el-form-item label="品牌名称" prop="tmName">
        <!-- 
          v-model 收集表单数据
        -->
        <el-input class="trademark-input" v-model="trademarkFormData.tmName" />
        <el-upload
          class="avatar-uploader"
          action="/app-dev/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkFormData.logoUrl"
            :src="trademarkFormData.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过200kb</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 具名插槽footer -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
export default {
  name: "XTrademark",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps, FormRules, FormInstance } from "element-plus";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  getTrademarkListApi,
  saveTrademarkApi,
  updateTrademarkApi,
  removeTrademarkApi,
} from "@/api/product/trademark";
import type {
  TrademarkList,
  TrademarkItem,
} from "@/api/product/model/trademarkModel";

// 删除品牌
const delTrademark = (row: TrademarkItem) => {
  ElMessageBox.confirm(`您确认要删除 ${row.tmName} 数据吗?`, "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await removeTrademarkApi(row.id);
    ElMessage.success("删除品牌成功");
    getTrademarkList(); // 重新获取数据展示
  });
};

// 显示添加品牌
const showSaveDialog = () => {
  visible.value = true;
  trademarkFormData.tmName = "";
  trademarkFormData.logoUrl = "";
  trademarkFormData.id = 0;
  trademarkFormRef.value?.clearValidate(); // 清空表单校验结果
};
// 显示修改品牌
const showUpdateDialog = (row: TrademarkItem) => {
  visible.value = true;
  trademarkFormData.tmName = row.tmName;
  trademarkFormData.logoUrl = row.logoUrl;
  trademarkFormData.id = row.id; // 将来发送更新请求需要id
  trademarkFormRef.value?.clearValidate(); // 清空表单校验结果
};

// ref语法的用法，用来获取组件实例对象
const trademarkFormRef = ref<FormInstance>();

// 提交表单
const submitForm = () => {
  // 触发表单校验
  // value?.validate 可选链语法，value有值就会调用validate，每值就不会调用
  trademarkFormRef.value?.validate(async (valid) => {
    // valid为true，代表表单校验通过
    if (valid) {
      const { tmName, logoUrl, id } = trademarkFormData;
      if (id) {
        // 发送请求，修改品牌
        await updateTrademarkApi({ tmName, logoUrl, id });
      } else {
        // 发送请求，添加品牌(更新服务器数据)
        await saveTrademarkApi(tmName, logoUrl);
      }
      // 清空表单数据
      // trademarkFormRef.value?.resetFields();
      ElMessage.success(`${id ? "修改" : "添加"}品牌成功`);
      // 隐藏对话框
      visible.value = false;
      // 重新发送请求，获取最新的数据展示（更新客户端数据）
      getTrademarkList();
    }
  });
};
// 表单数据
const trademarkFormData = reactive({
  // 定义表单数据名称：要求发送请求携带参数名称一致，要和数据源保证一致
  id: 0,
  tmName: "",
  logoUrl: "",
});

// 表单校验的规则: 规则名称，必须和表单数据名称一致
const trademarkFormRules = reactive<FormRules>({
  tmName: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
  logoUrl: [{ required: true, message: "请上传品牌logo", trigger: "blur" }],
});

const imageUrl = ref("");

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // 上传成功，更新表单数据
  trademarkFormData.logoUrl = response.data;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // rawFile 上传的图片文件
  // rawFile.type 图片类型
  // rawFile.size 图片大小
  const typeFiles = ["image/jpeg", "image/jpg", "image/png"];
  if (!typeFiles.includes(rawFile.type)) {
    ElMessage.error("上传图片格式必须是jpg或png!");
    return false; // 不会上传图片
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("上传图片大小不能超过200kb!");
  }
  return true;
};

// 对话框显示&隐藏
const visible = ref(false);

// 品牌列表数据
const trademarkList = ref<TrademarkList>([]);

// 当前页码
const currentPage = ref(1);
// 每页条数
const pageSize = ref(3);
// 总数
const total = ref(0);

// 封装一个用来发送请求，获取品牌列表的函数
const getTrademarkList = async () => {
  const result = await getTrademarkListApi(currentPage.value, pageSize.value);
  trademarkList.value = result.records;
  total.value = result.total;
};

onMounted(() => {
  getTrademarkList();
});

// 当currentPage发生变化时触发
const handleCurrentChange = (newCurrentPage: number) => {
  currentPage.value = newCurrentPage;
  getTrademarkList();
};

// 当page-size发生变化时触发
const handleSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize;
  getTrademarkList();
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
